import React, { useCallback, useMemo, useState, useRef } from 'react'
import MultiHull from './multiHull'
import Game from './game'
import Hull from './hull'
import TurningPoint from './turningPoint'
import ZeroLag from './zeroLag'
import CustomTrade from './customTrade'
import TrendChangeYiHaHa from './trendChangeYiHaHa'
import FixedInvestment from './fixedInvestment'
import Spring from './spring'
import ZigLag from './zigLag'

const strategies = [

  // MultiHull,
  TurningPoint,
  ZeroLag,
  CustomTrade,
  TrendChangeYiHaHa,
  FixedInvestment,
  Spring,
  ZigLag,
  Game,
  Hull]
const base = 1000000
export const BASE_CAPITAL = base
class Trader {
    constructor(props){
        this.props = props;
        this.cash = base;
        this.position = 0;
        this.positionCount = 0;
        this.costBasis = 0;
        this.realizedProfit = 0;
    }
    reset(){
        this.positionCount = 0;
        this.costBasis = 0;
        this.realizedProfit = 0;
        this.price = 0;
        this.cash = base;
        this.position = 0;
        this.props.setProfit(0);
        this.props.setCumulativeReturn(0);
    }
    updateMetrics(){
        const lastPrice = this.price ?? 0;
        const positionValue = this.positionCount * lastPrice;
        const totalAssets = this.cash + positionValue;
        const cumulativeReturn = ((totalAssets - base) / base) * 100;
        const unrealized = this.positionCount > 0 ? positionValue - this.costBasis : 0;
        const totalProfit = this.realizedProfit + unrealized;
        this.props.setCumulativeReturn(cumulativeReturn);
        this.props.setProfit(totalProfit);
        return { totalAssets, cumulativeReturn, totalProfit };
    }
    buy(price){
        const count = Math.floor(this.cash / price);
        if (count <= 0) {
            return;
        }
        this.positionCount = count;
        const cost = count * price;
        this.costBasis = cost;
        this.cash = this.cash - cost;
        this.price = price;

        const { totalAssets, cumulativeReturn, totalProfit } = this.updateMetrics();
        console.log(`买入后总资产: ${totalAssets}, 累积收益率: ${cumulativeReturn}%, 累计收益: ${totalProfit}`);
    }
    sell(price) {
        if (this.positionCount <= 0) {
            return;
        }
        const sellValue = this.positionCount * price;
        const profit = sellValue - this.costBasis; // 计算单次收益
        // 保存成本基础用于计算收益率（在重置前）
        const avgCostPrice = this.positionCount > 0 ? this.costBasis / this.positionCount : price;
        this.realizedProfit += profit;
        this.cash = this.cash + sellValue;
        this.positionCount = 0;
        this.price = price;
        this.position = 0;
        this.costBasis = 0;

        const { totalAssets, cumulativeReturn, totalProfit } = this.updateMetrics();
        console.log(`卖出后总资产: ${totalAssets}, 累积收益率: ${cumulativeReturn}%, 累计收益: ${totalProfit}`);
        
        // 返回平均成本价，用于计算收益率
        return avgCostPrice;
    }
    hold(price){
        this.price = price;
        const { totalAssets, cumulativeReturn, totalProfit } = this.updateMetrics();
        console.log(`持仓时总资产: ${totalAssets}, 累积收益率: ${cumulativeReturn}%, 累计收益: ${totalProfit}`);
    }
    get price(){
        return this._price
    }
    set price(p){
        this._price = p
        const positionValue = this.positionCount * p
        this._position = positionValue
        this.props.setPosition(positionValue)
        this.updateMetrics()
    }
    get cash(){
        return this._cash
    }
    get position(){
        return this._position
    }
    get positionCount(){
        return this._positionCount
    }
    get equity(){
        return (this.cash ?? 0) + (this.position ?? 0)
    }
    set cash(cash){
        this._cash = cash
        this.props.setCash(cash)
    }
    set position(position){
        this._position = position
        this.props.setPosition(position)
    }
    set positionCount(positionCount){
        this._positionCount = positionCount
    }
}

const calcSummary = (history, trades) => {
    if (!history || history.length < 2) {
        const wins = trades.filter(t => t > 0).length
        const losses = trades.filter(t => t <= 0).length
        return {
            winRate: 0,
            maxDrawdown: 0,
            totalReturn: 0,
            maxReturn: 0,
            annualReturn: 0,
            tradeCount: trades.length,
            wins,
            losses
        }
    }
    const equities = history.map(item => item.equity)
    const timestamps = history.map(item => item.timestamp ?? Date.now())
    const startEquity = equities[0]
    const endEquity = equities[equities.length - 1]
    const totalReturn = ((endEquity - startEquity) / startEquity) * 100
    let peak = equities[0]
    let maxDrawdown = 0
    equities.forEach(value => {
        if (value > peak) {
            peak = value
        }
        const drawdown = peak === 0 ? 0 : (peak - value) / peak
        if (drawdown > maxDrawdown) {
            maxDrawdown = drawdown
        }
    })
    const maxEquity = Math.max(...equities)
    const maxReturn = ((maxEquity - startEquity) / startEquity) * 100
    // 兼容旧格式（只有数字）和新格式（对象）
    const profitRatios = trades.map(t => typeof t === 'number' ? t : t.profitRatio)
    const wins = profitRatios.filter(p => p > 0).length
    const losses = profitRatios.filter(p => p <= 0).length
    const winRate = profitRatios.length ? (wins / profitRatios.length) * 100 : 0
    const startTs = timestamps[0]
    const endTs = timestamps[timestamps.length - 1]
    const totalDays = Math.max(1, (endTs - startTs) / (1000 * 3600 * 24))
    const annualReturn = totalDays > 0 ? ((endEquity / startEquity) ** (365 / totalDays) - 1) * 100 : totalReturn
    return {
        winRate,
        maxDrawdown: maxDrawdown * 100,
        totalReturn,
        maxReturn,
        annualReturn,
        tradeCount: trades.length,
        wins,
        losses
    }
}

// 统一的买卖标记管理器
export const useTradeMarkers = (chartRef) => {
    const tradeMarkersInfoRef = useRef([]) // 存储标记信息 {timestamp, type, value}
    const tradeMarkersRef = useRef([]) // 存储 overlay ID

    // 添加买卖标记
    // price: 可选，交易价格（默认使用 candle.close）
    const addTradeMarker = useCallback((candle, type, price = null) => {
        if (!chartRef?.current || !candle) return null
        try {
            const markerValue = type === 'buy' ? candle.low : candle.high
            const tradePrice = price !== null ? price : candle.close
            const label = type === 'buy' 
                ? `买入\n${tradePrice.toFixed(2)}` 
                : `卖出\n${tradePrice.toFixed(2)}`
            const markerId = chartRef.current.createOverlay({
                name: 'simpleAnnotation',
                extendData: label,
                points: [{ timestamp: candle.timestamp, value: markerValue }],
                styles: {
                    annotation: {
                        text: {
                            color: type === 'buy' ? '#0dd697' : '#f44336',
                            backgroundColor: type === 'buy' ? 'rgba(13,214,151,0.2)' : 'rgba(244,67,54,0.2)',
                            borderColor: type === 'buy' ? '#0dd697' : '#f44336',
                            textAlign: 'center'
                        }
                    }
                }
            })

            // 保存标记信息，用于重新绘制
            if (markerId) {
                tradeMarkersInfoRef.current.push({
                    timestamp: candle.timestamp,
                    type,
                    value: markerValue,
                    price: tradePrice
                })
                tradeMarkersRef.current.push(markerId)
            }

            return markerId
        } catch (e) {
            console.warn('Failed to create trade marker:', e)
            return null
        }
    }, [chartRef])

    // 重新绘制所有买卖标记（在 applyNewData 后调用）
    const redrawTradeMarkers = useCallback(() => {
        if (!chartRef?.current) return

        // 清除旧的 overlay ID
        tradeMarkersRef.current.forEach(id => {
            try {
                chartRef.current.removeOverlay(id)
            } catch (e) {
                // ignore
            }
        })
        tradeMarkersRef.current = []

        // 重新创建所有买卖标记
        tradeMarkersInfoRef.current.forEach(markerInfo => {
            try {
                // 如果价格信息缺失（旧版本创建的标记），使用标记位置的 value 作为价格
                const price = markerInfo.price !== undefined && markerInfo.price !== null 
                    ? markerInfo.price 
                    : (markerInfo.value || 0)
                const label = markerInfo.type === 'buy' 
                    ? `买入\n${price.toFixed(2)}` 
                    : `卖出\n${price.toFixed(2)}`
                const markerId = chartRef.current.createOverlay({
                    name: 'simpleAnnotation',
                    extendData: label,
                    points: [{ timestamp: markerInfo.timestamp, value: markerInfo.value }],
                    styles: {
                        annotation: {
                            text: {
                                color: markerInfo.type === 'buy' ? '#0dd697' : '#f44336',
                                backgroundColor: markerInfo.type === 'buy' ? 'rgba(13,214,151,0.2)' : 'rgba(244,67,54,0.2)',
                                borderColor: markerInfo.type === 'buy' ? '#0dd697' : '#f44336',
                                textAlign: 'center'
                            }
                        }
                    }
                })
                if (markerId) {
                    tradeMarkersRef.current.push(markerId)
                }
            } catch (e) {
                console.warn('Failed to redraw trade marker:', e)
            }
        })
    }, [chartRef])

    // 清除所有标记
    const clearTradeMarkers = useCallback(() => {
        if (!chartRef?.current) return
        tradeMarkersRef.current.forEach(id => {
            try {
                chartRef.current.removeOverlay(id)
            } catch (e) {
                // ignore
            }
        })
        tradeMarkersRef.current = []
        tradeMarkersInfoRef.current = []
    }, [chartRef])

    return {
        addTradeMarker,
        redrawTradeMarkers,
        clearTradeMarkers
    }
}

export const useStrategyBacktest = () => {
    const [equityHistory, setEquityHistory] = useState([])
    const [trades, setTrades] = useState([])
    const [summaryVisible, setSummaryVisible] = useState(false)
    const [summary, setSummary] = useState(null)
    const [finalized, setFinalized] = useState(false)

    const recordEquity = useCallback((timestamp, equity) => {
        setEquityHistory(prev => [...prev, { timestamp: timestamp ?? Date.now(), equity }])
    }, [])

    const registerTrade = useCallback((profitRatio, entryPrice = null, exitPrice = null) => {
        setTrades(prev => [...prev, {
            profitRatio,
            entryPrice,
            exitPrice
        }])
    }, [])

    const reset = useCallback(() => {
        setEquityHistory([])
        setTrades([])
        setSummary(null)
        setSummaryVisible(false)
        setFinalized(false)
    }, [])

    const finalize = useCallback(() => {
        if (finalized) return
        // 为了兼容 calcSummary，提取 profitRatio 数组
        const profitRatios = trades.map(t => typeof t === 'number' ? t : t.profitRatio)
        const stats = calcSummary(equityHistory, profitRatios)
        // 添加完整交易详情以便调试和显示
        stats.trades = trades
        console.log('回测总结:', {
            tradeCount: trades.length,
            trades: trades.map((t, i) => {
                const profitRatio = typeof t === 'number' ? t : t.profitRatio
                return { 
                    index: i + 1, 
                    profitRatio, 
                    profitPercent: (profitRatio * 100).toFixed(2) + '%',
                    entryPrice: typeof t === 'object' ? t.entryPrice : null,
                    exitPrice: typeof t === 'object' ? t.exitPrice : null
                }
            }),
            wins: stats.wins,
            losses: stats.losses,
            winRate: stats.winRate.toFixed(2) + '%',
            totalReturn: stats.totalReturn.toFixed(2) + '%'
        })
        setSummary(stats)
        setSummaryVisible(true)
        setFinalized(true)
    }, [equityHistory, trades, finalized])

    const SummaryModal = useMemo(() => {
        if (!summaryVisible || !summary) return null
        return (
            <div style={{
                position: 'fixed',
                top: 0,
                left: 0,
                right: 0,
                bottom: 0,
                background: 'rgba(0,0,0,0.45)',
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
                zIndex: 10000
            }}>
                <div style={{
                    width: 320,
                    borderRadius: 16,
                    border: '1px solid rgba(255,255,255,0.12)',
                    background: 'rgba(20,24,34,0.95)',
                    padding: 24,
                    color: '#FFFFFF'
                }}>
                    <div style={{fontSize: 16, marginBottom: 12}}>回测总结</div>
                    <div style={{display: 'flex', flexDirection: 'column', gap: 8, fontSize: 13}}>
                        <div>胜率：{summary.winRate.toFixed(2)}%</div>
                        <div>最大回撤：{summary.maxDrawdown.toFixed(2)}%</div>
                        <div>总收益率：{summary.totalReturn.toFixed(2)}%</div>
                        <div>最大收益率：{summary.maxReturn.toFixed(2)}%</div>
                        <div>年化收益率：{summary.annualReturn.toFixed(2)}%</div>
                        <div>交易次数：{summary.tradeCount}（盈利 {summary.wins}，亏损 {summary.losses}）</div>
                        {summary.trades && summary.trades.length > 0 && (
                            <div style={{marginTop: 8, paddingTop: 8, borderTop: '1px solid rgba(255,255,255,0.1)', fontSize: 11}}>
                                <div style={{marginBottom: 4}}>交易详情：</div>
                                <div style={{maxHeight: 200, overflowY: 'auto'}}>
                                    {summary.trades.map((trade, idx) => {
                                        const profitRatio = typeof trade === 'number' ? trade : trade.profitRatio
                                        const entryPrice = typeof trade === 'object' ? trade.entryPrice : null
                                        const exitPrice = typeof trade === 'object' ? trade.exitPrice : null
                                        return (
                                            <div key={idx} style={{color: profitRatio > 0 ? '#f44336' : '#0dd697', marginBottom: 2}}>
                                                交易 {idx + 1}: {(profitRatio * 100).toFixed(2)}%
                                                {entryPrice != null && exitPrice != null && (
                                                    <span style={{color: 'rgba(255,255,255,0.6)', marginLeft: 8}}>
                                                        ({entryPrice.toFixed(2)} → {exitPrice.toFixed(2)})
                                                    </span>
                                                )}
                                            </div>
                                        )
                                    })}
                                </div>
                            </div>
                        )}
                    </div>
                    <div style={{display: 'flex', justifyContent: 'flex-end', gap: 12, marginTop: 20}}>
                        <button onClick={() => setSummaryVisible(false)}>关闭</button>
                        <button onClick={() => { setSummaryVisible(false); window.location.reload() }}>返回首页</button>
                    </div>
                </div>
            </div>
        )
    }, [summaryVisible, summary])

    return {
        equityHistory,
        recordEquity,
        registerTrade,
        reset,
        finalize,
        finalized,
        SummaryModal,
        hideSummary: () => setSummaryVisible(false)
    }
}

export default {strategies, Trader}
